import { Component, OnInit } from '@angular/core';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { ApiService } from '@core/services/http/api.service';
import { dateFormat } from '../../../../../utils/utils';
import { BiService } from '../../../bi.service';

@Component({
  selector: 'outsourcing-analysisw',
  templateUrl: './outsourcing-analysis.component.html',
  styleUrls: ['./outsourcing-analysis.component.scss'],
})
export class OutsourcingAnalysisComponent implements OnInit {

  // 外协分析

  // 分析
  outsourcingOption: any = {
    tooltip: {
      trigger: 'item',
      formatter: this.showTooltip,
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll',
    },
    series: [
      {
        name: '品类', type: 'pie', center: ['60%', '50%'], radius: '50%', emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  outsourcingField: FormlyFieldConfig[] = [
    {
      key: 'DEPT_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAll',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          multiple: true,
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
          rowSelection: 'multiple',
          addSame: false,
          uniqueKey: 'id',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 5,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  outsourcingData: any;
  outsourcingModel: any = {};
  outsourcingLoading: boolean = false;

  // 金额
  amountOption: any = {
    tooltip: {
      trigger: 'item',
      // axisPointer: {
      //   type: 'cross',
      //   crossStyle: {
      //     color: '#999',
      //   },
      // },
      formatter: this.showAmountOptionTooltip,
    },
    legend: {
      data: ['内部外协单利润', '内部外协单成本', '内部外协单金额', '外采外协单利润', '外采外协单成本', '外采外协单金额', '同比', '环比'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '金额',
        type: 'value',
        axisLabel: {
          formatter: '{value} 元',
        },
      },
      {
        name: '比例',
        type: 'value',
        axisLabel: {
          formatter: '{value} %',
        },
      },
    ],
    series: [
      { name: '内部外协单利润', type: 'bar', stack: '内部外协单', emphasis: { focus: 'series' } },
      { name: '内部外协单成本', type: 'bar', stack: '内部外协单', emphasis: { focus: 'series' } },
      // { name: '内部外协单金额', type: 'bar', emphasis: { focus: 'series' } },
      { name: '外采外协单利润', type: 'bar', stack: '外部外协单', emphasis: { focus: 'series' } },
      { name: '外采外协单成本', type: 'bar', stack: '外部外协单', emphasis: { focus: 'series' } },
      // { name: '外采外协单金额', type: 'bar', emphasis: { focus: 'series' } },
      { name: '同比', type: 'line', yAxisIndex: 1 },
      { name: '环比', type: 'line', yAxisIndex: 1 },
    ],
  };
  amountData: any;
  amountLoading: boolean = false;

  // 排名
  rankData: any;
  rankLoading: boolean = false;

  //派工时效分析
  agingOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['总单量', '超时单量', '时效'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '金额',
        type: 'value',
        axisLabel: {
          formatter: '{value} 单',
        },
      },
      {
        name: '比例',
        type: 'value',
        axisLabel: {
          formatter: '{value} 分钟',
        },
      },
    ],
    series: [
      { name: '总单量', type: 'bar' },
      { name: '超时单量', type: 'bar' },
      { name: '时效', type: 'line', yAxisIndex: 1 },
    ],
  };
  agingField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  agingData: any;
  agingModel: any = {};
  agingLoading: boolean = false;

  // 员工
  staffData: any;
  staffLoading: boolean = false;

  constructor(
    private apiService: ApiService,
    private bi: BiService,
  ) {

  }

  ngOnInit() {
    setTimeout(() => {
      this.refreshOutsourcingData();
      this.refreshAgingData();
      this.refreshAmountData(null);
    }, 1000);
  }

  showTooltip(params) {
    let tooltip = params.seriesName + '<br/>' + params.name + ':' + params.data[1] + '(' + params.percent + '%)';
    return tooltip;
  }

  refreshOutsourcingData() {
    let date = this.bi.conversionMonths(this.outsourcingModel['DATE']);
    let id = this.outsourcingModel['DEPT_ID'] ? this.outsourcingModel['DEPT_ID'] : [];

    const data = {
      DEPT_ID: id,
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let api = 'fn.out.area1PieChart';

    this.outsourcingLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('外协分析', body);
      let dimensions = [];
      let source = [];
      if (body && body.length != 0) {
        body.forEach((res) => {
          let name = res['CLASS_NAME'] + '(' + res['CLASS_ID'] + ')';
          dimensions.push(name);
          source.push([
            name,
            res['AMOUNT'],
            res['CLASS_ID'],
          ]);
        });
      }
      this.outsourcingData = {
        dataset: {
          dimensions: dimensions,
          source: source,
        },
      };
      this.outsourcingLoading = false;
    });

    this.refreshAmountData(null);
  }

  clickOutsourcingChart(event) {
    // console.log(event);
    let id = event.data[2];
    this.refreshAmountData(id);
  }

  showAmountOptionTooltip(params) {
    let tooltip =
      '<div class="apes-charts-tooltip-p"><span style="background: #5470c6;" class="apes-charts-tooltip-span"></span>' +
      '内部外协销售利润 :' + '<span class="apes-charts-tooltip-text">' + params.data[1] + '</span></div>' +
      '<div class="apes-charts-tooltip-p"><span style="background: #91cc75;" class="apes-charts-tooltip-span"></span>' +
      '内部外协单成本 :' + '<span class="apes-charts-tooltip-text">' + params.data[2] + '</span></div>' +
      '<div class="apes-charts-tooltip-p"><span style="background: #fc8452;" class="apes-charts-tooltip-span"></span>' +
      '内部外协销售金额 :' + '<span class="apes-charts-tooltip-text">' + params.data[7] + '</span></div>' +
      '<div class="apes-charts-tooltip-p"><span style="background: #fac858;" class="apes-charts-tooltip-span"></span>' +
      '外采销售利润 :' + '<span class="apes-charts-tooltip-text">' + params.data[3] + '</span></div>' +
      '<div class="apes-charts-tooltip-p"><span style="background: #ee6666;" class="apes-charts-tooltip-span"></span>' +
      '外采外协单成本 :' + '<span class="apes-charts-tooltip-text">' + params.data[4] + '</span></div>' +
      '<div class="apes-charts-tooltip-p"><span style="background: #9a60b4;" class="apes-charts-tooltip-span"></span>' +
      '外采销售金额 :' + '<span class="apes-charts-tooltip-text">' + params.data[8] + '</span></div>' +
      '<div class="apes-charts-tooltip-p"><span style="background: #ea7ccc;" class="apes-charts-tooltip-span"></span>' +
      '外协销售总金额 :' + '<span class="apes-charts-tooltip-text">' + params.data[9] + '</span></div>' +
      '<div class="apes-charts-tooltip-p"><span style="background: #73c0de;" class="apes-charts-tooltip-span"></span>' +
      '同比 :' + '<span class="apes-charts-tooltip-text">' + params.data[5] + '</span></div>' +
      '<div class="apes-charts-tooltip-p"><span style="background: #3ba272;" class="apes-charts-tooltip-span"></span>' +
      '环比 :' + '<span class="apes-charts-tooltip-text">' + params.data[6] + '</span></div>';

    return tooltip;
  }

  refreshAmountData(classId) {
    let date = this.bi.conversionMonths(this.outsourcingModel['DATE']);
    let id = this.outsourcingModel['DEPT_ID'] ? this.outsourcingModel['DEPT_ID'] : [];

    const data = {
      // CLASS_ID: classId,
      DEPT_ID: id,
      DATE_START: date[0],
      DATE_END: date[1],
    };

    if (classId != null) {
      data['CLASS_ID'] = classId;
    }

    let amountApi = 'fn.out.area1Grid';

    this.amountLoading = true;
    this.apiService.post(amountApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
        console.log('外协金额分析', body);
        // let dimensions = [];
        let source = [['mouth','SALE_INCOME','PRICE_COST','V_SALE_INCOME','V_PRICE_COST','YEAR_RATE','MOUTH_RATE','SALE_AMOUNT','V_SALE_AMOUNT','ALL_AMOUNT']];
        if (body && body.length != 0) {
          body.forEach((res) => {
            // dimensions.push(res['mouth']);
            source.push([
              res['mouth'],
              res['SALE_INCOME'],                                // 内部外协销售利润
              res['PRICE_COST'],                                 // 内部外协单成本
              res['V_SALE_INCOME'],                              // 外采外协销售利润
              res['V_PRICE_COST'],                               // 外采外协单成本
              res['YEAR_RATE'],                                  // 同比
              res['MOUTH_RATE'],                                 // 环比
              res['SALE_AMOUNT'],                                // 内部外协销售金额
              res['V_SALE_AMOUNT'],                              // 外采外协销售金额
              res['SALE_AMOUNT'] + res['V_SALE_AMOUNT'],         // 外协销售总金额
            ]);
          });
        }
        this.amountData = {
          dataset: {
            // dimensions: dimensions,
            source: source,
          },
        };
        this.amountLoading = false;
      },
    );

    let rankApi = 'fn.out.area1BarChart';

    this.rankLoading = true;
    this.rankData = [];
    this.apiService.post(rankApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
        console.log('外协员工分析', body);
        if (body && body.length != 0) {
          this.rankData = body;
        }
        this.rankLoading = false;
      },
    );
  }

  refreshAgingData() {
    let date = this.bi.conversionMonths(this.agingModel['DATE']);

    const data = {
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let agingApi = 'fn.out.area2Bar';

    this.agingLoading = true;
    this.apiService.post(agingApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
        // console.log('派工时效分析', body);
        // let dimensions = [];
        let source = [['mouth','AMOUNT','B_AMOUT','TIME']];
        if (body && body.length != 0) {
          body.forEach((res) => {
              // dimensions.push(res['mouth']);
              source.push([
                res['mouth'],
                res['AMOUNT'],
                res['B_AMOUT'],
                res['TIME'],
              ]);
            },
          );
        }
        this.agingData = {
          dataset: {
            // dimensions: dimensions,
            source: source,
          },
        };
        this.agingLoading = false;
      },
    );

    let staffApi = 'fn.out.area2Grid';
    this.staffLoading = true;
    this.staffData = [];
    this.apiService.post(staffApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
        // console.log('派工时效员工分析', body);
        if (body && body.length != 0) {
          this.staffData = body;
        }
        this.staffLoading = false;
      },
    );
  }

  showStaffText(oldT, newT, type = false) {
    let showText = '--';
    if (oldT && oldT != '--') {
      let t;
      if (oldT > newT) {
        t = oldT - newT;
      } else if (oldT < newT) {
        t = newT - oldT;
      } else {
        t = '--';
      }
      if (type && t != '--') {
        showText = t.toFixed(2);
      } else {
        showText = t;
      }
    }
    return showText;
  }

  showStaffClass(oldT, newT) {
    let showClass = 'noChange';
    if (oldT && oldT != '--') {
      if (oldT > newT) {
        showClass = 'showDown';
      } else if (oldT < newT) {
        showClass = 'showUp';
      } else {
        showClass = 'noChange';
      }
    }
    return showClass;
  }

}

